var lhsList = new Array();
var rhsList = new Array();
Array.prototype.contains = function (element) {
	   for (var i = 0; i < this.length; i++) {
		   try{
	       if (this[i] == element || this[i].id == element.id) {
	    	   return true;
	       }
		   }catch(ex){}
	   }
	   return false;
	}

var paymentTerms = [ {id: "US00", desc:"US00-Net 1 Day"},
                     {id: "US01", desc:"US01-Net 2 Days"},
                     {id: "US02", desc:"US02-1% discount if paid within 10 days, Net 30 days"},
                     {id: "US03", desc:"US03-Net 3 Days"},
                     {id: "US04", desc:"US04-2% discount if paid within 10 days, Net 30 Days"},
                     {id: "US05", desc:"US05-Net 5 days"},
                     {id: "US06", desc:"US06-2% discount if paid within 15 days, Net 30 Days"},
                     {id: "US07", desc:"US07-2% discount if paid within 20 days, Net 30 Days"},
                     {id: "US08", desc:"US08-1% discount if paid within 15 days, Net 30 Days"},
                     {id: "US09", desc:"US09-2% discount if paid within 10 days, Net 11 Days"},
                     {id: "US10", desc:"US10-Net 10 days"},
                     {id: "US11", desc:"US11-1.5% discount if paid within 10 days, Net 16 Days"},
                     {id: "US12", desc:"US12-1% discount if paid within 14 days, Net 15 Days"},
                     {id: "US13", desc:"US13-2% discount if paid within 15 days, Net 16 Days"},
                     {id: "US14", desc:"US14-3% discount if paid within 10 days, Net 30 Days"},
                     {id: "US15", desc:"US15-Net 15 days"},
                     {id: "US16", desc:"US16-0.5% discount if paid within 10 days, Net 30 Days"},
                     {id: "US17", desc:"US17-2% discount if paid within 10 days, Net 31 Days"},
                     {id: "US18", desc:"US18-10% discount if paid within 10 days, Net 30 Days"},
                     {id: "US19", desc:"US19-5% discount if paid within 20 days, Net 30 Days"},
                     {id: "US20", desc:"US20-Net 20 days"},
                     {id: "US21", desc:"US21-2% discount if paid within 15 days, Net 60 Days"},
                     {id: "US22", desc:"US22-1% discount if paid within 30 days, Net 31 Days"},
                     {id: "US30", desc:"US30-Net 30 days"},
                     {id: "US50", desc:"US50-Net 50 days"},
                     {id: "US40", desc:"US40-Net 40 Days"},
                     {id: "US45", desc:"US45-Net 45 Days"},
                     {id: "US60", desc:"US60-Net 60 Days"}
                    ];



function rhsTransfer(isSourceCache){
	var selectedValues = new Array();
	lhsList = new Array();
	if(isSourceCache){
		selectedValues = usr_comp_cache.paymentTerms;
	} else{
		selectedValues = dwr.util.getValue("reg_compPaymentTerms");
	}
	
	
	
	for	(var i=0;i<paymentTerms.length;i++){
		var paymentTerm = paymentTerms[i];
		
		for(var j=0;j<selectedValues.length;j++){
			var selectedId = selectedValues[j];
			if(selectedId == paymentTerm.id){
				rhsList.push(paymentTerm);
			} 
		}
	}
	

	for	(var i=0;i<paymentTerms.length;i++){
		var paymentTerm = paymentTerms[i];
		
		if(!rhsList.contains(paymentTerm)){
			lhsList.push(paymentTerm);
		}
	}
	sortPaymentListArray();
	dwr.util.removeAllOptions("reg_compPaymentTerms");
	dwr.util.removeAllOptions("reg_compPaymentTermsSelected");
	dwr.util.addOptions("reg_compPaymentTerms", lhsList, "id", "desc");
	dwr.util.addOptions("reg_compPaymentTermsSelected", rhsList, "id", "desc");
}

function lhsTransfer(){
	
	var selectedValues = new Array();
	rhsList = new Array();
	selectedValues = dwr.util.getValue("reg_compPaymentTermsSelected");
	if(selectedValues != null && selectedValues.length > 0){
		for(var i=0;i<selectedValues.length;i++){
			var selectedId = selectedValues[i];
			lhsList.push(getPaymentTerm(selectedId));
			//lhsList.sort();
			
		}
	}
	
	for	(var i=0;i<paymentTerms.length;i++){
		var paymentTerm = paymentTerms[i];
		
		if(!lhsList.contains(paymentTerm)){
			rhsList.push(paymentTerm);
		}
	}
	
	sortPaymentListArray();
	dwr.util.removeAllOptions("reg_compPaymentTerms");
	dwr.util.removeAllOptions("reg_compPaymentTermsSelected");
	dwr.util.addOptions("reg_compPaymentTerms", lhsList, "id", "desc");
	dwr.util.addOptions("reg_compPaymentTermsSelected", rhsList, "id", "desc");
	
}

function getPaymentTerm(id){
	
	for	(var i=0;i<paymentTerms.length;i++){
		var paymentTerm = paymentTerms[i];
		
		if(paymentTerm.id == id ){
			return paymentTerm;
		}
	}
}

function sortPaymentListArray(){
	
	lhsList.sort(
			function(a,b) {
				if ((a.id+"") < (b.id+"")) { return -1; }
				if ((a.id+"") > (b.id+"")) { return 1; }
				return 0;
			}	
	);
	
	rhsList.sort(
			function(a,b) {
				if ((a.id+"") < (b.id+"")) { return -1; }
				if ((a.id+"") > (b.id+"")) { return 1; }
				return 0;
			}	
	);
}




function open_mng_comp_prof(){
	u_hideAllSections();
	u_safeShowElement('comp_mgmt_div');
	populatecomp_locYuiTable();
	populateCommPref();
	
	dwr.util.setValue('commgm_cname',usr_comp_cache.companyName);
	dwr.util.setValue('commgm_ctaxid',usr_comp_cache.companyTaxId);
	dwr.util.setValue('commgm_cssn',usr_comp_cache.companySSN);
	
	dwr.util.setValue('reg_lob',usr_comp_cache.companyDomain);
	
	dwr.util.setValue('reg_CompanyContact',usr_comp_cache.contact);
	dwr.util.setValue('reg_compAddressLine1',usr_comp_cache.addressLine1);
	dwr.util.setValue('reg_compAddressLine2',usr_comp_cache.addressLine2);
	dwr.util.setValue('reg_compCity',usr_comp_cache.city);
	dwr.util.setValue('reg_compState',usr_comp_cache.state);
	dwr.util.setValue('reg_compZip',usr_comp_cache.zip);
	dwr.util.setValue('reg_compCountry',usr_comp_cache.country);
	 
	dwr.util.setValue('reg_compCountry',usr_comp_cache.country);
	try{
	dwr.util.setValue('reg_areaCodePhone',usr_comp_cache.phone.substring(0,2));
	dwr.util.setValue('reg_areaCodePhoneNumber',usr_comp_cache.phone.substring(3));
	}catch(ex){}
	
	dwr.util.setValue('reg_compEmail',usr_comp_cache.email);
	//	reg_areaCodeFax+
	dwr.util.setValue('reg_compURL',usr_comp_cache.URL);
	dwr.util.setValue('reg_compCurrency',usr_comp_cache.currency);
	
	try{
	rhsTransfer(true);	
	dwr.util.setValue('commgm_reg_idValue',usr_comp_cache.otherRegvalue);
	dwr.util.setValue('company_reg_idType',usr_comp_cache.otherRegId);
	}catch(ex){}
	
	if(!isNavigationFromBackButton){
	var functionPointerObj = new Object();
	functionPointerObj.functionName = "open_mng_comp_prof()";
	navigationStateArray.push(functionPointerObj);
	}
	 
	 
	
	
	
}



function open_mng_usr(){
	u_hideAllSections();
	u_safeShowElement('user_mgmt_div');
	tn_getUserProfilesForCompany(usr_comp_cache.companyId);
	
	if(!isNavigationFromBackButton){
	var functionPointerObj = new Object();
	functionPointerObj.functionName = "open_mng_usr()";
	navigationStateArray.push(functionPointerObj);
	}
}

function open_mng_clnt(){
	u_hideAllSections();
	u_safeShowElement('client_mgmt_div');
	getClientsList(usr_comp_cache.companyId);
	
	if(!isNavigationFromBackButton){
	var functionPointerObj = new Object();
	functionPointerObj.functionName = "open_mng_clnt()";
	navigationStateArray.push(functionPointerObj);
	}
}

function show_comp_admin_links(){
	if(companyAdmin == "Y"){
		u_safeShowElement('li_comp_profile');
		u_safeShowElement('li_supp_mgmt');
		u_safeShowElement('li_usr_mgmt');
		u_safeShowElement('li_client_mgmt');
	}else{
		u_safeHideElement('li_comp_profile');
		u_safeHideElement('li_supp_mgmt');
		u_safeHideElement('li_usr_mgmt');
		u_safeHideElement('li_client_mgmt');
	}
}

var complocColdef = [ {key : "selectthis" , label : "Select" , formatter : "radio"},
                     { key: "addressLine1", label: "Address Line 1"},
                { key: "addressLine2", label: "Address Line 2"},
                { key: "city", label: "City"},
                { key: "state", label: "State"},
                { key: "zip", label: "Zip"},
                { key: "billingAddress", label: "Used for Billing?"},
                { key: "shippingAddress", label: "Used for Shipping?"},
                { key : "locationId", hidden: true}];
var complocDataSource = new YAHOO.util.DataSource();
var complocyuitable = null;

function populatecomp_locYuiTable(){
	complocDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
	if(complocyuitable == null){
		complocyuitable = new YAHOO.widget.DataTable(
				"yui_comp_locations_table",
				complocColdef,
				complocDataSource,
				{});
		
		// Selects any cell that receives a checkbox click
		complocyuitable.subscribe("radioClickEvent", function(oArgs) {
		    var elCheckbox = oArgs.target;
		    if(elCheckbox.checked) {
		        var elCell = this.getTrEl(elCheckbox);
		        var rec = this.getRecordSet().getRecord(elCell.id);
		        dwr.util.setValue('comp_locid',rec.getData('locationId'));
		    }
		});
		
		complocyuitable.set("selectionMode", "single");
		complocyuitable.subscribe("rowClickEvent", complocyuitable.onEventSelectRow);
	
	}
	
	if(complocyuitable != null && complocyuitable.getRecordSet() != null && complocyuitable.getRecordSet().getLength() > 0){
		complocyuitable.deleteRows(0,complocyuitable.getRecordSet().getLength());
	}
	
	complocyuitable.addRows(usr_comp_cache.locations);
	dwr.util.setValue('comp_locid','');
	
}



var loc_dialog = null;
function open_loc_dialog(){
	dwr.util.setValue('comp_compid',usr_comp_cache.companyUniqueIdentifier);
	
	var loc_id = dwr.util.getValue('comp_locid');
	
	
	if(!isEmptyString(loc_id)){
		var loc = null;
		for(var i=0;i<usr_comp_cache.locations.length;i++){
			if(loc_id == usr_comp_cache.locations[i].locationId){
				loc = usr_comp_cache.locations[i];
				break;
			}
		}
		dwr.util.setValue('comp_addrl1',loc.addressLine1);
		dwr.util.setValue('comp_addrl2',loc.addressLine2);
		dwr.util.setValue('comp_city',loc.city);
		dwr.util.setValue('comp_state',loc.state);
		dwr.util.setValue('comp_zip',loc.zip);
		if(loc.billingAddress == "Yes"){
			document.getElementById('comp_isbilling').checked = true;
		}else{
			document.getElementById('comp_isbilling').checked = false;
		}
		if(loc.shippingAddress == "Yes"){
			document.getElementById('comp_isshipping').checked = true;
		}else{
			document.getElementById('comp_isshipping').checked = false;
		}
	}else{
		dwr.util.setValue('comp_addrl1','');
		dwr.util.setValue('comp_addrl2','');
		dwr.util.setValue('comp_city','');
		dwr.util.setValue('comp_state','');
		dwr.util.setValue('comp_zip','');
		dwr.util.setValue('comp_zip','');
		dwr.util.setValue('comp_zip','');
	}
	//width:"1024px",height:"500px"
	if (loc_dialog == null) {
		loc_dialog = new YAHOO.widget.Dialog(
			'comp_loc_dialog', {
				width : "450px",
				/*effect : {
					effect : YAHOO.widget.ContainerEffect.FADE,
					duration : 0.25
				},*/
				constraintoviewport : true, 
				fixedcenter : true,
				modal : true,
				visible : true,
				draggable : true
			});

	var handleCancel = function() {
		this.cancel();
	};

	var handleSubmit = function() {
		var addr = {
				locationId : dwr.util.getValue('comp_locid'),
				addressLine1 : dwr.util.getValue('comp_addrl1'),
				addressLine2: dwr.util.getValue('comp_addrl2'),
				city: dwr.util.getValue('comp_city'),
				state: dwr.util.getValue('comp_state'),
				zip: dwr.util.getValue('comp_zip'),
				billingAddress : "No",
				shippingAddress : "No"
		}
		
		if(document.getElementById('comp_isbilling').checked){
			addr.billingAddress = "Yes";
		}
		
		if(document.getElementById('comp_isshipping').checked){
			addr.shippingAddress = "Yes";
		}
		
		if(isEmptyString(addr.locationId)){
			addr.locationId = null;
		}
		
		var cid = dwr.util.getValue('comp_compid');
		
		var dcmd = {
				callback : success_setupdateloc,
				exceptionHandler : exception_generic_handler,
				timeout : 100000,
				errorHandler : exception_generic_handler	
		};
		
		DWR_UserManagement.addUpdateDeleteLocation(addr,cid,false,
				dcmd);
		
		this.cancel();
	};
	var dlgButtons = [ {
		text : "Save",
		handler : handleSubmit
	}, {
		text : "Cancel",
		handler : handleCancel,
		isDefault : true
	} ];
	loc_dialog.cfg.queueProperty("buttons", dlgButtons);
	loc_dialog.render();
	}
	loc_dialog.show();
	document.getElementById('comp_loc_dialog').style.display = 'block';
}

function success_setupdateloc(dwrresp){
	if(dwrresp != null && dwrresp.respCode == 0 && dwrresp.objRespOrError != null){
		usr_comp_cache = dwrresp.objRespOrError;
		populatecomp_locYuiTable();
	}
}

function open_del_loc(){
	var loc_id = dwr.util.getValue('comp_locid');
	if(isEmptyString(loc_id)){
		alert('Please select a location.');
		return;
	}
	var conf = confirm('Are you sure you want to delete this Address?');
	if(conf){
		var dcmd = {
				callback : success_setupdateloc,
				exceptionHandler : exception_generic_handler,
				timeout : 100000,
				errorHandler : exception_generic_handler	
		};
		var cid = usr_comp_cache.companyUniqueIdentifier;
		
		addr = {locationId : loc_id };
		DWR_UserManagement.addUpdateDeleteLocation(addr,cid,true,
				dcmd);
	}
}

var pmtterm_dialog = null;
function open_pmtterm_dialog(){
	dwr.util.setValue('comp_compyid',usr_comp_cache.companyUniqueIdentifier);
	
	var loc_id = dwr.util.getValue('comp_pmttermid');
	
	
	if(!isEmptyString(loc_id)){
		var loc = null;
		for(var i=0;i<usr_comp_cache.paymentTerms.length;i++){
			if(loc_id == usr_comp_cache.paymentTerms[i].id){
				loc = usr_comp_cache.paymentTerms[i];
				break;
			}
		}
		dwr.util.setValue('comp_pmttermname',loc.uniqueName);
		dwr.util.setValue('comp_pmttermdescr',loc.description);
	}else{
		dwr.util.setValue('comp_pmttermname','');
		dwr.util.setValue('comp_pmttermdescr','');
	}
	
	if (pmtterm_dialog == null) {
		pmtterm_dialog = new YAHOO.widget.Dialog(
			'comp_pmtterm_dialog', {
				width : "450px",
				/*effect : {
					effect : YAHOO.widget.ContainerEffect.FADE,
					duration : 0.25
				},*/
				constraintoviewport : true, 
				fixedcenter : true,
				modal : true,
				visible : true,
				draggable : true
			});

	var handleCancel = function() {
		this.cancel();
	};

	var handleSubmit = function() {
		var pmtterm = {
				id : dwr.util.getValue('comp_pmttermid'),
				uniqueName : dwr.util.getValue('comp_pmttermname'),
				description: dwr.util.getValue('comp_pmttermdescr')
		}
		
		if(isEmptyString(pmtterm.id)){
			pmtterm.id = null;
		}
		
		var cid = usr_comp_cache.companyUniqueIdentifier;
		
		var dcmd = {
				callback : success_setupdateptterms,
				exceptionHandler : exception_generic_handler,
				timeout : 100000,
				errorHandler : exception_generic_handler	
		};
		
		DWR_UserManagement.addUpdateDeletePaymentTerms(pmtterm,cid,false,
				dcmd);
		
		this.cancel();
	};
	var dlgButtons = [ {
		text : "Save",
		handler : handleSubmit
	}, {
		text : "Cancel",
		handler : handleCancel,
		isDefault : true
	} ];
	pmtterm_dialog.cfg.queueProperty("buttons", dlgButtons);
	pmtterm_dialog.render();
	}
	pmtterm_dialog.show();
	document.getElementById('comp_pmtterm_dialog').style.display = 'block';
}

function success_setupdateptterms(dwrresp){
	if(dwrresp != null && dwrresp.respCode == 0 && dwrresp.objRespOrError != null){
		usr_comp_cache = dwrresp.objRespOrError;
		
	}
}


function open_del_pmtterm(){
	var loc_id = dwr.util.getValue('comp_pmttermid');
	if(isEmptyString(loc_id)){
		alert('Please select a payment term.');
		return;
	}
	var conf = confirm('Are you sure you want to delete this Payment Term?');
	if(conf){
		var dcmd = {
				callback : success_setupdateptterms,
				exceptionHandler : exception_generic_handler,
				timeout : 100000,
				errorHandler : exception_generic_handler	
		};
		var cid = usr_comp_cache.companyUniqueIdentifier;
		
		var pmtterm = {id : loc_id };
		DWR_UserManagement.addUpdateDeletePaymentTerms(pmtterm,cid,true,
				dcmd);
	}
}

YAHOO.widget.DataTable.addPaymentLineFormatter = function(elLiner, oRecord, oColumn, oData) {
    elLiner.innerHTML = "<a href=\"javascript:add_paymentTerms('"+ oRecord.getId()+"');\"  >Add</a>";
};

YAHOO.widget.DataTable.paymentText = function(elLiner, oRecord, oColumn, oData) {
	elLiner.innerHTML = "<input type='text' value='' onblur=\"javascript:setYuiTablePaymentValue(this.value,'"+ oRecord.getId()+"','"+oColumn.getKey()+"');\">" ;
};

function setYuiTablePaymentValue(value,id,col){
	var rs = comppmttermyuitable.getRecordSet()
	rs.updateRecordValue(rs.getRecord(id),col,value);
	console.log(id);
}

function add_paymentTerms(recordId){
	var record = comppmttermyuitable.getRecordSet().getRecord(recordId);
	console.log(record);
	comppmttermyuitable.addRow(splitEmptyPaymentTerms); //
}

var comppmttermColdef = [ 
                         
{
	key : "uniqueName",
	label : "Payment Term Name",
	formatter:YAHOO.widget.DataTable.paymentText,
	width : "100px"
	
},

{
	key : "description",
	label : "Payment Term Description",
	formatter:YAHOO.widget.DataTable.paymentText,
	width : "100px"
	
},

{
	key : "action",
	label : "Action",
	formatter:YAHOO.widget.DataTable.addPaymentLineFormatter,
	width : "100px"
	
},

{
	key : "id", hidden: true
	
}
                          
 ];
 var comppmttermDataSource = new YAHOO.util.DataSource();
 var comppmttermyuitable = null;
 var splitEmptyPaymentTerms = {uniqueName: "", description: "", id: ""};
 


var customNameFormatter = function(elLiner, oRecord, oColumn, oData) {
	elLiner.innerHTML = oRecord.getData("lastName") + ", " + oRecord.getData("firstName") ;
};

var customNameFormatter2 = function(elLiner, oRecord, oColumn, oData) {
	elLiner.innerHTML = oRecord.getData("communicationMode") ;
};

var userProfileListColdef = [ {key : "id" , hidden: true},
                              {key : "userName" , label : "User Name" , width: "20px", formatter: customNameFormatter},
                              {key : "emailAddress" , label : "Email Address" , width: "30px"},
                              {key : "superUser" , label : "Super User" , formatter : "checkbox", width: "10px"},
                              {key : "createPO" , label : "Create<br> PO" , formatter : "checkbox", width: "10px"},
                              {key : "changePO" , label : "Edit<br> PO" , formatter : "checkbox", width: "10px"},
                              {key : "cancelPO" , label : "Cancel<br> PO" , formatter : "checkbox", width: "10px"},
                              {key : "createInvoices" , label : "Create <br> Invoice" , formatter : "checkbox", width: "10px"},
                              {key : "postPayments" , label : "Post<br> Payments" , formatter : "checkbox", width: "10px"},
                              {key : "restrictByDocNumber" , label : "Rest Doc#" , formatter : "checkbox", maxwidth: "10px"},
                              {key : "verified" , label : "Is Verfied" , formatter : "checkbox", width: "10px"}
                    ];

var userProfileYuiTableInstance = null;
var userProfileDataSource = YAHOO.util.DataSource();

function populateUserProfileYuiTable(userProfileList){
	userProfileDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
	if(userProfileYuiTableInstance == null){
		userProfileYuiTableInstance = new YAHOO.widget.DataTable(
				"userListByCompany_YUI_Table_Div",
				userProfileListColdef,
				userProfileDataSource,
				{});
		
		// Selects any cell that receives a checkbox click
		userProfileYuiTableInstance.subscribe("checkboxClickEvent", function(oArgs) {
		    var elCheckbox = oArgs.target;
		    if(elCheckbox.checked) {
		        var elCell = this.getTrEl(elCheckbox);
		        var rec = this.getRecordSet().getRecord(elCell.id);
		       
		    }
		});
		
		userProfileYuiTableInstance.set("selectionMode", "none");
		//userProfileYuiTableInstance.subscribe("checkboxClickEvent", userProfileYuiTableInstance.onEventSelectRow);
		userProfileYuiTableInstance.subscribe("checkboxClickEvent", function(oArgs){ 
			var elCheckbox = oArgs.target; 
			var oRecord = this.getRecord(elCheckbox); 
			var colKey = this.getColumn(elCheckbox).getKey();
			oRecord.setData(colKey,elCheckbox.checked);
			oRecord.setData("updated",true);
		}); 
	}
	if(userProfileList != null){
		//Check for Super Users.
		for(var k=0;k<userProfileList.length;k++){
			var p = userProfileList[k];
			if(usr_comp_cache != null && usr_comp_cache.companyProfileAdmins != null && usr_comp_cache.companyProfileAdmins.length > 0){
				for(var m=0;m<usr_comp_cache.companyProfileAdmins.length;m++){
					if(p.userProfileId == usr_comp_cache.companyProfileAdmins[m]){
						p.superUser = true;
						break;
					}
				}
			}
		}
		
		if(userProfileYuiTableInstance != null && userProfileYuiTableInstance.getRecordSet() != null 
				&& userProfileYuiTableInstance.getRecordSet().getLength() > 0){
			userProfileYuiTableInstance.deleteRows(0,userProfileYuiTableInstance.getRecordSet().getLength());
		}
		userProfileYuiTableInstance.addRows(userProfileList);
	}
}

function tn_getUserProfilesForCompany(companyId){
	searchObj = "";
	var config = {
			callback : success_getUserProfilesForCompany,
			exceptionHandler : exception_generic_handler,
			timeout : 100000,
			errorHandler : exception_generic_handler	
	};
	
	DWR_UserManagement.getUserProifileByCompany(companyId,config);
}

function success_getUserProfilesForCompany(responseObj){
	if(responseObj.respCode == 0){
		populateUserProfileYuiTable(responseObj.objRespOrError);
	}
}

function update_user_roles(){
	if(userProfileYuiTableInstance == null || userProfileYuiTableInstance.getRecordSet().getLength() <= 0){
		alert("Nothing to Update.");
	}else{
		var rset = userProfileYuiTableInstance.getRecordSet();
		var rlen = userProfileYuiTableInstance.getRecordSet().getLength();
		var updArr = new Array();
		var anythingUpdated = false;
		for(var i=0;i<rlen;i++){
			if(rset.getRecord(i).getData("updated") != undefined && rset.getRecord(i).getData("updated") == true){
				updArr.push(rset.getRecord(i)._oData);
				anythingUpdated = true;
			}
		}
		
		if(anythingUpdated){
			turnThrobberOn('Updating User Profile');
			var config = {
					callback : success_updateUserProfiles,
					exceptionHandler : exception_generic_handler,
					timeout : 100000,
					errorHandler : exception_generic_handler	
			};
			DWR_UserManagement.updateUserProperties(updArr,config);
		}else{
			alert('Nothing to update.');
		}
	}
}

function success_updateUserProfiles(dwrresp){
	turnThrobberOff();
}

function open_mng_user_prof(){
	u_hideAllSections();
	u_safeShowElement('registration_div_edit');
	tn_populateUserProfile();
	if(!isNavigationFromBackButton){
	var functionPointerObj = new Object();
	functionPointerObj.functionName = "open_mng_user_prof()";
	navigationStateArray.push(functionPointerObj);
	}
	
}

function tn_populateUserProfile(){
	
	dwr.util.setValue("username",loggedinuser);// = loggedinuser;//usr_profile_cache.emailAddress;
	//dwr.util.setValue("password")
	dwr.util.setValue("fname",usr_profile_cache.firstName);
	dwr.util.setValue("lname",usr_profile_cache.lastName);
	dwr.util.setValue("addr_line1",usr_profile_cache.addressLine1);
	dwr.util.setValue("addr_line2",usr_profile_cache.addressLine2);
	dwr.util.setValue("city",usr_profile_cache.city);
	dwr.util.setValue("state",usr_profile_cache.state) ;
	dwr.util.setValue("zip",usr_profile_cache.zip);
	dwr.util.setValue("areaPhone",usr_profile_cache.workPhone.substring(0,3)) ;
	dwr.util.setValue("phoneNumber",usr_profile_cache.fax.substring(3));
	dwr.util.setValue("areaFax",usr_profile_cache.fax.substring(0,3));
	dwr.util.setValue("faxNumber",usr_profile_cache.fax.substring(3)) ;
	dwr.util.setValue("username_confirm",usr_profile_cache.emailAddress);
	dwr.util.setValue("country",usr_profile_cache.country);
	dwr.util.setValue("deliveryNote",usr_profile_cache.deliveryInfo);
	
}

var fldmapEditUser = [ 
               {fid : "fname", required : true},
               {fid : "lname", required : true},
               {fid : "addr_line1", required : true},
               {fid : "city", required : true},
               {fid : "state", required : true},
               {fid : "zip", required : true}
               //{fid : "password", required : true}
              ];


function tn_reg_validate(){
	var isvalid = true;
	for(var i=0;i<fldmapEditUser.length;i++){
		var fld = fldmapEditUser[i];
		if(fld && fld['required']&& isEmptyField(fld['fid'])){
			u_safeSetText_ChangeClass(fld['fid'],'','form-validation-error');
			isvalid = false;
		} else{
			//u_safeSetText_ChangeClass(fld['fid'],'','');
			//
		}
	}
	
	return isvalid;
}

function tn_updateUserProfile(){
	if(tn_reg_validate()){
		//dwr call to update
		
		var regXfer = {}
		regXfer.fname = dwr.util.getValue("fname");
		regXfer.lname = dwr.util.getValue("lname");
		regXfer.addressLine1 = dwr.util.getValue("addr_line1");
		regXfer.addressLine2 = dwr.util.getValue("addr_line2");
		regXfer.city = dwr.util.getValue("city");
		regXfer.state = dwr.util.getValue("state");
		regXfer.zip = dwr.util.getValue("zip");
		regXfer.workPhone = dwr.util.getValue("areaPhone")+dwr.util.getValue("phoneNumber");
		regXfer.fax = dwr.util.getValue("areaFax")+dwr.util.getValue("faxNumber");
		regXfer.country = dwr.util.getValue("country");
		regXfer.deliveryInfo = dwr.util.getValue("deliveryNote");
		//regXfer.password = dwr.util.getValue("password");
		
		var dwrCallMetaData = { 
				  callback:tn_cb_updateUser_success, 
				  exceptionHandler: exception_generic_handler,
				  timeout: 100000,
				  errorHandler:  exception_generic_handler
		};
		turnThrobberOn('Updating User Profile');
		DWR_Register.updateUser(regXfer,usr_profile_cache.userProfileId,dwrCallMetaData);
		
		
	} else{
		alert("Complete All req field");
	}
}

function tn_reg_changeCSSClass(obj){
	try{
		if(obj.value != ""){
			u_safeSetText_ChangeClass(obj.id,obj.value,'');
		} else{
			u_safeSetText_ChangeClass(obj.id,'','form-validation-error');
		}
	}catch(ex){
		alert(ex);
	}
}

function tn_cb_updateUser_success(responseObj){
	turnThrobberOff();
	if(responseObj.respCode == 0){
		usr_profile_cache = responseObj.objRespOrError;
		alert("User Details Updated successfully!!");
	}
}

function tn_updateCompany(){

var cid = usr_comp_cache.companyId;
var regXfer = {};
regXfer.companyName = dwr.util.getValue("commgm_cname");
regXfer.companyLOB = dwr.util.getValue("reg_lob");
regXfer.companyTaxId = dwr.util.getValue("commgm_ctaxid");
regXfer.companySsn = dwr.util.getValue("commgm_cssn");
regXfer.companyaddressLine1 = dwr.util.getValue("reg_compAddressLine1");
regXfer.companyaddressLine2 = dwr.util.getValue("reg_compAddressLine2");
regXfer.companyContact = dwr.util.getValue("reg_CompanyContact");
regXfer.companyCity = dwr.util.getValue("reg_compCity");
regXfer.companyState = dwr.util.getValue("reg_compState");
regXfer.companyZip = dwr.util.getValue("reg_compZip");
regXfer.companyPhoneNumber = dwr.util.getValue("reg_areaCodePhone")+dwr.util.getValue("reg_areaCodePhoneNumber");
regXfer.companyFaxNumber = dwr.util.getValue("reg_areaCodeFax")+dwr.util.getValue("reg_areaCodeFaxNumber");
regXfer.companyEmail = dwr.util.getValue("reg_compEmail");
regXfer.companyCountry = dwr.util.getValue("reg_compCountry");
regXfer.companyURL = dwr.util.getValue("reg_compURL");
regXfer.companyCurrency = dwr.util.getValue("reg_compCurrency");
regXfer.otherRegId = dwr.util.getValue("company_reg_idType");
regXfer.otherRegvalue = dwr.util.getValue("commgm_reg_idValue");
regXfer.companyPaymentTerms = getSelectedPaymentTerms();
regXfer.emailPreferences = getEmailCommPreference();
regXfer.faxPreferences = getFaxCommPreference();

var dwrCallMetaData = { 
		  callback:tn_cb_updateCompany_success, 
		  exceptionHandler: exception_generic_handler,
		  timeout: 100000,
		  errorHandler:  exception_generic_handler
};
//turnThrobberOn('Updating Company Profile');
DWR_Register.updateCompany(cid,regXfer,dwrCallMetaData);
}

function getSelectedPaymentTerms(){
	var paymentTermsArray = new Array();
	for(var i=0;i<rhsList.length;i++){
		paymentTermsArray.push(rhsList[i].id); 
	}
	return paymentTermsArray;
}

function tn_cb_updateCompany_success(responseObj){
	turnThrobberOff();
	if(responseObj.respCode == 0){
		usr_comp_cache = responseObj.objRespOrError;
		alert("Company Details Updated successfully!!");
	} else{
		turnThrobberOff();
		alert("Error in Updating Company");
	}
	populateCommPref();
}

var commPreferenceYUITableInstance = null;
//var commPreferenceCache = "";



var commPrefYUIDatatable;
var commPrefDS = new YAHOO.util.DataSource();

function populateCommPref() {
	if(usr_comp_cache.emailPreferences == null){
		usr_comp_cache.emailPreferences = new Array();
		var r1 = {communicationMode:"Email",posent:false,poreceived:false,invsent:false,invreceived:false,pymtsent:false,pymtreceived:false,crdsent:false,crdreceived:false};
		usr_comp_cache.emailPreferences.push(r1);
	} else{
		usr_comp_cache.emailPreferences.communicationMode = "Email";
	}
	
	if(usr_comp_cache.faxPreferences == null){
		usr_comp_cache.faxPreferences = new Array();
		var r2 = {communicationMode:"Fax",posent:false,poreceived:false,invsent:false,invreceived:false,pymtsent:false,pymtreceived:false,crdsent:false,crdreceived:false};
		usr_comp_cache.faxPreferences.push(r2);
		//usr_comp_cache.commPreferences.push(r2);
	}else{
		usr_comp_cache.faxPreferences.communicationMode = "FAX";
	}
        var commColumnDefs = [
                            {key:"communicationMode", label:"Communication Mode"},
                            {label:"Purchase Order", children: [
                                   {key:"posent", label:"Sent",sortable:true, resizeable:true,formatter: "checkbox"},
                                   {key:"poreceived", label:"Received",sortable:true, resizeable:true,formatter: "checkbox"}
                               ]
                             },
                           {label:"Invoices", formatter : "checkbox", 
                           	children: [
                                  {key:"invsent", label:"Sent",sortable:true, resizeable:true},
                                  {key:"invreceived", label:"Received",sortable:true, resizeable:true}
                              ]},
                          {label:"Payment", formatter : "checkbox", 
                          	children: [
                                 {key:"pymtsent", label:"Sent",sortable:true, resizeable:true},
                                 {key:"pymtreceived", label:"Received",sortable:true, resizeable:true}
                             ]},
                          {label:"Credit Memo", formatter : "checkbox", 
                          	children: [
                                 {key:"crdsent", label:"Sent",sortable:true, resizeable:true},
                                 {key:"crdreceived", label:"Received",sortable:true, resizeable:true}
                             ]}
                        ];

       
        commPrefDS.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
       
        commPrefYUIDatatable = new YAHOO.widget.DataTable("yui_comp_communication_preference_table", commColumnDefs, commPrefDS,{});
        commPrefYUIDatatable.subscribe("checkboxClickEvent", function(oArgs) {
		    var elCheckbox = oArgs.target;
		    var oRecord = this.getRecord(elCheckbox); 
			var colKey = this.getColumn(elCheckbox).getKey();
			oRecord.setData(colKey,elCheckbox.checked);
		});
        commPrefYUIDatatable.addRow(usr_comp_cache.emailPreferences);
        commPrefYUIDatatable.addRow(usr_comp_cache.faxPreferences);
}


function getEmailCommPreference(){
	return commPrefYUIDatatable.getRecordSet().getRecords()[0].getData();
}
function getFaxCommPreference(){
	return commPrefYUIDatatable.getRecordSet().getRecords()[1].getData();
}


